using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using SiteManager;
using System.Data.SqlClient;
using System.Text;
using System.Net.Mail;

// This page send e-mails to doctors. Only members are allowed to send e-mails.

// Author: Pawan Kamboj
// Dated : July 23 2007    
 
public partial class Doctor_EmailToDoctor : System.Web.UI.Page
{
    public int iDoctorId = -1; // public variable for doctor
    public int iPatientId=-1;

    Manager objManager = new Manager(true,"ConnectionString");
    
    protected void Page_Load(object sender, EventArgs e)
    {
        lblMessage.Text = "";

        if (!IsPostBack)
        {
            #region Check If patient is logged in.
            if (!Equals(Session["userType"], null))
            {
                // if the logged in user is SiteUser i.e. a patient then use session patient id.
                if (string.Compare(Session["userType"].ToString(), "SiteUser", true) == 0)
                {
                    iPatientId = Convert.ToInt32(Session["userID"]);
                }
            }
            
            ////removed this check on client requst on 1st Aug 2007

            //if (iPatientId <= 0)
            //{
            //    lblMessage.Text = "You are not logged in. Please login to send e-mail !";
            //    mvEmailToDoctor.ActiveViewIndex = -1;
            //}

            #endregion

            #region Get Doctor Id from Query String and check it against database
            if (Request.QueryString.HasKeys())
            {
                if (!Equals(Request.QueryString["Id"], null))
                {
                    if (Manager.IsNumeric(Request.QueryString["Id"].ToString()))
                    {
                        iDoctorId = Convert.ToInt32(Request.QueryString["Id"]);
                        SqlDataReader DR = objManager.ExecuteQuery("SELECT ID FROM tbl_Doctors WHERE IsDelete=0 AND ID=" + iDoctorId.ToString());
                        if (!DR.Read())
                            iDoctorId = -1;
                        DR.Close();
                        DR.Dispose();
                    }
                }
            }

            #endregion

            #region  If invalid Doctor Id, then show message and not allow to send e-mail
            if (iDoctorId > 0)
            {
                // If a valid doctor id is supplied then add it to vew state for further use
                ViewState.Add("iDoctorId", iDoctorId.ToString());
            }
            else
            {
                lblMessage.Text = "Invalid Doctor Id supplied !";
                mvEmailToDoctor.ActiveViewIndex = -1;
            }
            #endregion

            #region  If everything is OK , then show patient details if some patients has logged in

            Session["IsEmailSent"] = null;
            mvEmailToDoctor.SetActiveView(vwEmailForm);

            if (iPatientId > 0)
            {
                SqlDataReader DR_Patient = objManager.ExecuteQuery("SELECT Id,fName,LName,Email,Gender,Address1,City,ZipCode,State,CountryName, birthYear FROM tbl_Users, tbl_Country Where Countryid=CountryCode and Id=" + iPatientId.ToString());
                if (DR_Patient.Read())
                {
                    txtFirstName.Text = DR_Patient["fName"].ToString();
                    txtLastName.Text = DR_Patient["LName"].ToString();
                    txtStreet.Text = DR_Patient["Address1"].ToString();
                    txtCity.Text = DR_Patient["City"].ToString();
                    txtState.Text = DR_Patient["State"].ToString();
                    txtZip.Text = DR_Patient["ZipCode"].ToString();
                    txtCountry.Text = DR_Patient["CountryName"].ToString();
                    txtEmailAddress.Text = DR_Patient["Email"].ToString();
                    txtEmailAddress.ReadOnly = true; // made it readonly so that user can't change it as it should be not editable in case of registerd patient
                    rbtnPatientGender.ClearSelection(); // First clear the selection then set it accordingly
                    if (string.Compare(DR_Patient["Gender"].ToString(), "M", true) == 0)
                        rbtnPatientGender.Items.FindByText("Male").Selected = true;
                    else
                        rbtnPatientGender.Items.FindByText("Female").Selected = true;

                    if (Manager.IsNumeric(DR_Patient["birthYear"].ToString()))
                    {
                        int iTempAge = DateTime.Now.Year - Convert.ToInt32(DR_Patient["birthYear"]);
                        if (iTempAge > 1)
                            txtPatientAge.Text = iTempAge.ToString();
                    }
                }

                DR_Patient.Close();
                DR_Patient.Dispose();

            }
            #endregion
        }
        else
        {
            // If page is posted back then get Doctor Id from view state.
            iDoctorId = Convert.ToInt32(ViewState["iDoctorId"]);
        }        
    }


    protected void btnSendEmail_Click(object sender, EventArgs e)
    {
        #region Send e-mail to the doctor

        if (Equals(Session["IsEmailSent"], null) && iDoctorId > 0)
        {
            SqlDataReader DR = objManager.ExecuteQuery("SELECT fName, lName, Email FROM tbl_Doctors WHERE IsDelete=0 AND Len(Email) > 1 and ID=" + iDoctorId.ToString());
            if (DR.Read())
            {
                StringBuilder sbMailBody = new StringBuilder(string.Empty);
                sbMailBody.Append("Dr. " + DR["fName"].ToString() + " " + DR["lName"].ToString() + ", <br><br>");
                sbMailBody.Append("You have received a contact e-mail from a patient. Details are as follows:<br><br>");
                sbMailBody.Append("First Name: " + txtFirstName.Text + "<br>");
                sbMailBody.Append("Last Name: " + txtLastName.Text + "<br>");
                sbMailBody.Append("Address: " + txtStreet.Text + "<br>");
                sbMailBody.Append("City: " + txtCity.Text + "<br>");
                sbMailBody.Append("State: " + txtState.Text + "<br>");
                sbMailBody.Append("ZipCode: " + txtZip.Text + "<br>");
                sbMailBody.Append("Country: " + txtCountry.Text + "<br>");
                sbMailBody.Append("Email: " + txtEmailAddress.Text + "<br>");
                sbMailBody.Append("Gender: " + rbtnPatientGender.SelectedValue + "<br>");
                sbMailBody.Append("Age: " + txtPatientAge.Text + "<br>");
                sbMailBody.Append("What should the doctor know about the patient? <br>" + rdbtnAbout.SelectedValue + "<br><br>");
                sbMailBody.Append("What kind of procedure is the patient interested in? <br>" + txtProcedurIenterested.Text + "<br><br>");
                sbMailBody.Append("Thanks,<br>FindaDoc.com");

                string sEmailTo = DR["Email"].ToString();

                if (sEmailTo.Length > 0)
                {
                    // For testing set synapse e-mail
                    //sEmailTo = "synapsetesting@gmail.com";
                    
                    //Commented by Wahaj Khan Dated Jan 03 2012
                    //objManager.sendMail(sbMailBody.ToString(), sEmailTo, txtFirstName.Text + " " +txtLastName.Text, "FindaDoc.com - Patient Contact", txtEmailAddress.Text, "");

                    //Added by Wahaj Khan Dated Jan 03 2012-- START
                    string strMessageStatus = SendEmailToDoctorDentist(sbMailBody.ToString(), sEmailTo, txtFirstName.Text + " " + txtLastName.Text, "FindaDoc.com - Patient Contact", txtEmailAddress.Text);
                    if (strMessageStatus == "Send Successfully")
                    {
                        //Response.Write("Message Sent Successfully");
                        ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('Email Sent Successfully');", true);
                    }
                    else
                    {
                        // Response.Write(strMessageStatus);
                        ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('" + strMessageStatus + "');", true);
                    }
                    //Added by Wahaj Khan Dated Jan 03 2012-- END
                }

                sbMailBody = null;

                // Add flag to Session so that it can be detected and mail should not be sent again on refresh or on again button click.
                Session["IsEmailSent"] = "Yes";
                mvEmailToDoctor.SetActiveView(vwEmailSent);

                // Don't use redirect as it is handled by Session variable
                ////Response.Redirect("EmailToDoctor.aspx?Id=" + iDoctorId.ToString() + "&Status=MailSent", true);
            }
            else
            {
                lblMessage.Text = "Sorry, Can't send e-mail to this doctor!";
            }
            DR.Close();
            DR.Dispose();
        }
        else
        {
            lblMessage.Text = "Email Has Been Already Sent ! <br><br>";
            mvEmailToDoctor.SetActiveView(vwEmailSent);
        }
        
        #endregion

    }
    //Added by Wahaj Khan Dated Jan 03 2012-- START
    protected string SendEmailToDoctorDentist(string strBody, string strTo, string fromName, string strSubject, string strFrom)
    {
        SmtpClient smtpClient = new SmtpClient();
        MailMessage message = new MailMessage();
        try
        {
            message.From = new MailAddress(strFrom);
            message.Subject = strSubject;
            message.Body = strBody;
            message.IsBodyHtml = true;
            // smtpClient.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
            smtpClient.Host = "smtp.1and1.com"; //Or Your SMTP Server Address
            smtpClient.Credentials = new System.Net.NetworkCredential("docfriend@findadoc.com", "rateddoc56832013");
            message.To.Add(strTo);
            smtpClient.EnableSsl = true;
            smtpClient.Send(message);
            message = null;
            smtpClient = null;
            return "Send Successfully";
            //            The Host address is
            //www.1and1.com

            //username and password for the Domain Web Mail is
            //docfriend@findadoc.com
            //rateddoc


        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
    //Added by Wahaj Khan Dated Jan 03 2012-- END
}
